﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using QRCoder;

namespace WebAPI.Controllers
{
    /// <summary>
    /// Tool方法
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    public class ToolController : Controller
    {
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetQrCode")]
        public IActionResult GetQrCode(string text)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.Black, Color.White, true);

            MemoryStream ms = new MemoryStream();
            qrCodeImage.Save(ms, ImageFormat.Png);

            /*
             HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
             response.Content = new ByteArrayContent(ms.ToArray());
             response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
             //GET http://localhost:12345/qrcode?text=https://www.example.com
             return response;
             */

            /*返回响应时没有正确地设置响应消息的Content-Type类型 image/png */
            var response = File(ms.ToArray(), "image/png");
            return response;
        }
    }
}